package com.chengqj.config;

import org.bson.types.Decimal128;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.data.mongodb.core.convert.*;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.transaction.ChainedTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * Copyright © 2020年 com.qxkj. All rights reserved.
 *
 * @author chengqj
 * mongodb事务管理器配置
 * version 1.0.0 (接口必须带上)
 * @date 2020/11/5 16:43
 */
@Configuration
public class MongodbConfiguration {
    /**
     * 用户事务管理器
     * @param dbFactory
     * @return
     */
    @Bean("userMongoTransactionManager")
    MongoTransactionManager primaryMongoTransactionManager(@Qualifier("userMongoDbFactory") MongoDatabaseFactory dbFactory) {
        return new MongoTransactionManager(dbFactory);
    }
    /**
     * 订单事务管理器
     * @param dbFactory
     * @return
     */
    @Bean("orderMongoTransactionManager")
    MongoTransactionManager secondaryMongoTransactionManager(
            @Qualifier("orderMongoDbFactory") MongoDatabaseFactory dbFactory) {
        return new MongoTransactionManager(dbFactory);
    }

    /**
     *  多个事务管理器集成
     * @param ds1
     * @param ds2
     * @return
     */
    @Bean(name = "chainedTransactionManager")
    public ChainedTransactionManager transactionManager(
            @Qualifier("userMongoTransactionManager") PlatformTransactionManager ds1,
            @Qualifier("orderMongoTransactionManager") PlatformTransactionManager ds2) {

        return new ChainedTransactionManager(ds1, ds2);
    }

    /**
     * 去除数据中的class数据
     * @param factory
     * @param context
     * @param beanFactory
     * @return
     */
    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDatabaseFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
        try {
            mappingConverter.setCustomConversions(beanFactory.getBean(MongoCustomConversions.class));
        } catch (NoSuchBeanDefinitionException ignore) {
        }
        // Don't save _class to mongo
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return mappingConverter;
    }

}
